package com.cxw.healthserver.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.cxw.healthserver.entity.Exam
import com.cxw.healthserver.mapper.ExamMapper
import com.cxw.healthserver.response.BaseResponse
import org.json.JSONObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @createTime 2024/6/26 23:42
 * @author 崔兴旺
 * @description
 */
@Service
class ExamService : BaseService<Exam>() {

    @Autowired
    lateinit var examMapper: ExamMapper

    /**
     * 保存体检
     */
    fun saveExam(username: String, jsonStr: String): BaseResponse<Any> {
        val jsonObject = JSONObject(jsonStr)
        val sourceTableId: String = jsonObject.getString("sourceTableId")
        val idNumber = jsonObject.optString("idNumber", "")
        val queryWrapper = createQueryWrapper(username, idNumber)

        var exam = examMapper.selectOne(
            queryWrapper.eq("sourceTableId", sourceTableId)
        )
        var isAdd = false
        if (exam == null) {
            exam = Exam()
            exam.username = username
            exam.idNumber = idNumber
            exam.sourceTableId = sourceTableId
            isAdd = true
        }
        exam.json = jsonStr

        if (isAdd) {
            examMapper.insert(exam)
        } else {
            examMapper.updateById(exam)
        }
        return BaseResponse.success(null)
    }
}